﻿using System;
using System.Web;
using System.Web.Mvc;
using System.Globalization;
using System.Threading;

namespace Presentation.Web.UI.Attibutes
{
    // Inherit from AuthorizeAttribute is a hack to run it first.
    public class LanguageAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            HttpCookie cookie;
            if (filterContext.RouteData.Values["lang"] != null && !string.IsNullOrWhiteSpace(filterContext.RouteData.Values["lang"].ToString()))
            {
                var lang = filterContext.RouteData.Values["lang"].ToString();
                Thread.CurrentThread.CurrentCulture =CultureInfo.CreateSpecificCulture(lang);
                Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(lang);
            }
            else
            {
                cookie = filterContext.HttpContext.Request.Cookies["Presentation.Web.UI_CurrentUICulture"];
                string langHeader;
                if (cookie != null)
                {
                    langHeader = cookie.Value;
                    Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(langHeader);

                }
                else
                {
                    langHeader = filterContext.HttpContext.Request.UserLanguages[0].ToString();
                    Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(langHeader);

                }
                filterContext.RouteData.Values["lang"] = langHeader;
            }
            cookie = new HttpCookie("Presentation.Web.UI_CurrentUICulture", Thread.CurrentThread.CurrentUICulture.Name)
                         {Expires = DateTime.Now.AddYears(1)};
            filterContext.HttpContext.Response.SetCookie(cookie);
        }
    }
}
